package com.seed.manager;

import com.seed.core.action.Action;
import com.seed.core.pojo.seed.Seed;
import com.seed.core.Lib;
import org.springframework.web.bind.annotation.RequestMethod;

import java.util.HashMap;
import java.util.List;
import java.util.Map;
import java.util.concurrent.ConcurrentHashMap;

public class LibManager {
    private static final Map<String, Lib> libs = new ConcurrentHashMap<>();

    public static void set(Lib lib) {
        String libName = lib.getName();
        if(libs.get(libName) != null) {
            throw new RuntimeException(String.format("库【%s】已存在", libName));
        }

        libs.put(libName, lib);
    }

    public static Lib get(String libName) {
        Lib lib = libs.get(libName);
        if(lib == null) {
            throw new RuntimeException(String.format("库【%s】不存在", libName));
        }

        return lib;
    }

    public static Action getAction(String seedName, RequestMethod method, String actionName, List<String> libs) {
        if(libs == null || libs.isEmpty()) return null;

        for(String libName: libs) {
            Lib lib = LibManager.get(libName);
            Action action = lib.getAction(seedName, method, actionName);
            if(action != null) return action;
        }

        return null;
    }

    public static Map<String, Seed> getLibSeeds(List<String> libNames) {
        Map<String, Seed> ret = new HashMap<>();
        if(libNames != null) {
            for(String libName: libNames) {
                Lib lib = LibManager.get(libName);
                Map<String, Seed> libSeeds = lib.getSeeds();
                if(libSeeds != null) ret.putAll(libSeeds);
            }
        }

        return ret;
    }

    public static Map<String, Action> getLibActions(List<String> libNames) {
        Map<String, Action> ret = new HashMap<>();
        if(libNames != null) {
            for(String libName: libNames) {
                Lib lib = LibManager.get(libName);
                Map<String, Action> libActions = lib.getActions();
                if(libActions != null) ret.putAll(libActions);
            }
        }

        return ret;
    }
}
